<template>
    <a-drawer :title="title" :width="600" @close="handleCancel(false)" :visible="visible"
              :destroyOnClose="true"
              :maskClosable="false"
              :bodyStyle="{ paddingBottom: '60px' }">

        <a-form-model ref="ruleForm" :model="form" :rules="rules">

            <a-row :gutter="16">

                <a-col :span="16">

                    <a-form-model-item label="图文标题" prop="title" ref="title">
                        <a-input placeholder="请设置图文标题" v-model="form.title"/>
                    </a-form-model-item>

                </a-col>
                <a-col :span="8">
                    <a-form-model-item label="图文作者" prop="author" ref="author">
                        <a-input placeholder="请设置图文作者" v-model="form.author"/>
                    </a-form-model-item>

                </a-col>


                <a-col :span="16" class="sameHeight">

                    <a-form-model-item label="图文摘要" prop="digest" ref="digest">


                        <a-textarea placeholder="图文摘要" v-model="form.digest" :rows="5"/>
                    </a-form-model-item>

                </a-col>
                <a-col :span="8" class="sameHeight">


                    <a-form-model-item label="封面图片" prop="coverPicUrl" ref="coverPicUrl">

                        <a-row>
                            <a-col :span="16">

                                <a-upload name="file"
                                          list-type="picture-card"
                                          :show-upload-list="false"
                                          :before-upload="beforeUpload"
                                          @change="uploadHandler"
                                          :customRequest="customRequest">
                                    <img v-if="form.coverPicUrl" :src="form.coverPicUrl" class="PreviewImg"/>
                                    <div v-else>
                                        <a-icon :type="upLoading ? 'loading' : 'plus'"/>
                                        <div class="ant-upload-text">本地上传</div>
                                    </div>
                                </a-upload>

                            </a-col>
                            <a-col :span="8">
                                <span title="设置封面图片在正文页面的显示属性">可见设置</span>
                                <a-switch

                                        checked-children="显示" un-checked-children="隐藏"
                                        :defaultChecked="form.showCoverPic"
                                        @change="e=>form.showCoverPic=e"
                                />
                            </a-col>
                        </a-row>


                    </a-form-model-item>
                </a-col>


                <a-col :span="12">

                    <a-form-model-item label="所属分类" prop="typeCode" ref="typeCode">
                        <TypeSelector :pushTop="false" :value="form.typeCode" @onSelect="(e)=>{ form.typeCode=e }"/>
                    </a-form-model-item>

                </a-col>

                <a-col :span="12">

                    <a-form-model-item label="正文属性" prop="contentAttr" ref="contentAttr">
                        <a-radio-group v-model="form.contentAttr" default-value="HTML" button-style="solid"
                                       @change="form.content=null">
                            <a-radio-button value="HTML">富文本模式</a-radio-button>
                            <a-radio-button value="URL">链接模式</a-radio-button>

                        </a-radio-group>
                    </a-form-model-item>

                </a-col>


                <a-col :span="8">
                    <a-form-model-item label="显示排序" prop="sort" ref="sort">
                        <a-input v-model.number="form.sort"/>
                    </a-form-model-item>

                </a-col>

                <a-col :span="8">

                    <a-form-model-item label="阅读次数" prop="readCount" ref="readCount">
                        <a-input v-model.number="form.readCount"/>
                    </a-form-model-item>

                </a-col>

                <a-col :span="8">

                    <a-form-model-item label="分享次数" prop="shareCount" ref="shareCount">
                        <a-input v-model.number="form.shareCount"/>
                    </a-form-model-item>

                </a-col>


                <a-col :span="24" v-if="form.contentAttr==='URL'">

                    <a-form-model-item label="原文连接" prop="content" ref="content">
                        <a-input v-model="form.content" placeholder="请输入原文本连接的网页地址"/>
                    </a-form-model-item>

                </a-col>

                <a-col :span="24" v-else>
                    <a-form-model-item label="正文内容">

                        <RichEditor v-if="dataInit" :content="initContent" :uploadType="'system'" :height="300" @editorHandler="e=>form.content=e"/>


                    </a-form-model-item>
                </a-col>


            </a-row>


        </a-form-model>
        <!-- Modal 页脚 -->
        <footer class="drawer-footer">
            <a-button type="primary" :loading="loading" @click="onSubmit">保存</a-button>
        </footer>
    </a-drawer>
</template>
<script>

    import {fileUpload} from '../../../util/internal.api'
    import {newsFind, newsAdd, newsUpdate} from '../public/http.js';
    import {formRule} from './validator'


    export default {
        props: ['editRecord'],

        components: {
            TypeSelector: () => import('../component/TypeSelector'),

            RichEditor: () => import('../../../common/RichEditor'),

        },


        data() {
            return {
                upLoading: false,
                isUpdate: false, //是否是更新模式
                loading: false, //按钮Loading
                title: '新增图文分类',
                visible: true, //modal 显示状态
                initContent: "",
                dataInit: false,
                form: {
                    title: null,
                    author: null,
                    digest: null,
                    coverPicUrl: null,
                    showCoverPic: true,
                    contentAttr: "HTML",
                    typeCode: null,
                    content: "",
                    sort: 0,
                    readCount: 0,
                    shareCount: 0,


                },
                rules: formRule(),

            };
        },
        methods: {

            //表单提交事件
            onSubmit() {
                this.$refs.ruleForm.validate(valid => {
                    //验证成功后进行数据提交
                    if (valid) {
                        this.loading = true;
                        if (this.isUpdate) {
                            newsUpdate(this.form.id, this.form).then(res => {
                                this.$exMod.ajaxMessage(res);
                                if (res.code === 0) {
                                    this.handleCancel(true);
                                }
                            });
                        } else {
                            newsAdd(this.form).then(res => {
                                this.$exMod.ajaxMessage(res);
                                if (res.code === 0) {
                                    this.handleCancel(true);
                                }
                            });
                        }
                    }
                });
            },
            //关闭弹窗 刷新
            handleCancel(render = false) {
                this.visible = false;
                this.$emit('closeFun', {render: render});
            },
            //表单初始化

            //数据初始化
            async init() {

                let obj = {...this.editRecord};
                if (obj.id) {
                    this.isUpdate = true;
                    this.title = '编辑图文分类';
                    await newsFind(obj.id).then(res => {
                        res.code === 0 ? this.form = res.data.result : null;
                    })


                    this.initContent = this.form.content;


                }
                this.dataInit = true;

            },


            //=============================上传的方法=========================
            customRequest(data) {
                this.upLoading = true;
                const formData = new FormData();
                formData.append('file', data.file);
                fileUpload(formData).then(res => {
                    if (res.code === 0) {
                        this.form.coverPicUrl = res.data.url
                    } else {
                        this.$exMod.ajaxMessage(res);
                    }

                })
                this.upLoading = false;
            },
            beforeUpload(file) {
                const allowTye = ['bmp', 'png', 'jpeg', 'jpg', 'gif'];
                const fileType = file.type.split("/");
                const checkType = allowTye.findIndex((value, index, arr) => {
                    return value === fileType[1]
                });
                if (checkType < 0) {
                    this.$notification['error']({
                        message: '图片素材添加失败',
                        description: '图片素材只允许上传bmp,png、jpeg、jpg、gif格式的图片'
                    });
                    return false;
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$notification['error']({message: '图片素材添加失败', description: "图片素材的大小不能超过 2MB!"});
                    return false;
                }
                return true
            },
            uploadHandler(info) {
                if (info.file.status === 'done') {
                    this.$message.success(`${info.file.name} file uploaded successfully`);
                } else if (info.file.status === 'error') {
                    this.$message.error(`${info.file.name} file upload failed.`);
                }
            },


        },
        created() {
            this.init();
        }
    };
</script>
<style scoped>
    .sameHeight {
        height: 170px;
        overflow: hidden;
    }

    .ant-form-item {
        margin-bottom: 0 !important;
    }

    .PreviewImg {
        max-width: 100%;
        max-height: 150px;
        overflow: hidden;
    }
</style>
